//
//  HYCPushCitytroller.m
//  FamilyTravel
//
//  Created by dllo on 15/10/26.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HYCPushCitytroller.h"
#import "HYCHeadDocument.h"

#import "HYCSaveTool.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
#define SWIDTH [UIScreen mainScreen].bounds.size.width
#define SHEIGHT [UIScreen mainScreen].bounds.size.height
@interface HYCPushCitytroller ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) UIScrollView *scrollView;
@property(nonatomic, retain) NSMutableArray *arr;
@property(nonatomic, retain) NSMutableArray *scrArr;
@property(nonatomic, retain) NSMutableArray *lowArr;
@property(nonatomic, retain) MBProgressHUD *hud;




@end

@implementation HYCPushCitytroller

- (void)dealloc {
    [_collectionView release];
    [_scrollView release];
    [_arr release];
    [_scrArr release];
    [_hud release];
    [_lowArr release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.arr = [NSMutableArray array];
    self.lowArr = [NSMutableArray array];
    self.scrArr = [NSMutableArray array];
    
    if ([HYCSaveTool isModelInPlist:self.model]) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    } else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    }
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2.6785, HEIGHT / 3.51);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    //    flowLayout.sectionInset = UIEdgeInsetsMake(20, 10, 20, 10);
    flowLayout.sectionInset = UIEdgeInsetsMake(40, 25, 10, 25);
    flowLayout.headerReferenceSize = CGSizeMake(SWIDTH, SHEIGHT / 3.335);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    //    self.tableView.tableHeaderView = self.collectionView;
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[HYCPushCityCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[HYCPushCityCollReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    
    
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeAction) userInfo:nil repeats:YES];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"加载中...";
    [self createData];
    
}
// 收藏
- (void)click:(UIBarButtonItem *)button {
    
    if ([button.title isEqualToString:@"收藏"]) {
        
        UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"😄" message:@"收藏成功了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [aler show];
        
        
        [HYCSaveTool saveModelToPlist:self.model];
        button.title = @"已收藏";
        
    } else {
        
        
        
        [HYCSaveTool cancelModelInPlist:self.model];
        button.title = @"收藏";
        
        UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"😄" message:@"取消收藏成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [aler show];
        
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HYCPushDisDetailsController *pDVC = [[HYCPushDisDetailsController alloc] init];
    
    NSString *str = [NSString stringWithFormat:@"http://m.qyer.com/z/deal/%@/?source=app&client_id=qyer_ios&track_app_version=6.7&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8", [self.arr[indexPath.row] number]];
    
    pDVC.wStr = str;
    pDVC.title = @"折扣详情";
    [self.navigationController pushViewController:pDVC animated:YES];
    
    pDVC.hidesBottomBarWhenPushed = YES;
}

- (void)createData {
    
    NSString *urlOne = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?city_id=%@", self.model.number];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", urlOne, @"&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1"];
    
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        // 上面的四个coll
        for (NSDictionary *tempDic in dic[@"data"][@"local_discount"]) {
            HYCPushCityModel *movie = [[HYCPushCityModel alloc] init];
            [movie setValuesForKeysWithDictionary:tempDic];
            [self.arr addObject:movie];
            [movie release];
        }
        
        for (NSDictionary *tempDic in dic[@"data"][@"new_discount"]) {
            HYCPushCityModel *movie = [[HYCPushCityModel alloc] init];
            [movie setValuesForKeysWithDictionary:tempDic];
            [self.lowArr addObject:movie];
            [movie release];
        }
        for (HYCPushCityModel *model in self.lowArr) {
            [self.arr addObject:model];
        }
        
        // 轮播图
        self.scrArr = [NSMutableArray array];
        for (NSString *tempStr in dic[@"data"][@"photos"]) {
            HYCScrSecPushsecDisModel  *scrMovie = [[HYCScrSecPushsecDisModel alloc] init];
            scrMovie.photos = tempStr;
            [self.scrArr addObject:scrMovie];
            [scrMovie release];
        }
        
        UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, (SHEIGHT + 64) / 3)];
        [firstImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[self.scrArr.count - 1] photos]]];
        [self.scrollView addSubview:firstImageView];
        
        [firstImageView release];
        
        for (NSInteger i = 0; i < self.scrArr.count; i++) {
            UIImageView *scrImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH, (SHEIGHT + 64) / 3)];
            [scrImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[i] photos]]];
            [self.scrollView addSubview:scrImageView];
            scrImageView.userInteractionEnabled = YES;
            self.scrollView.bounces = NO;
            [scrImageView release];
        }
        
        
        
        UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * self.scrArr.count, 0, SWIDTH, (SHEIGHT + 64) / 3)];
        [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrArr[0] photos]]];
        [self.scrollView addSubview:lastImageView];
        [lastImageView release];
        lastImageView.userInteractionEnabled = YES;
        [self.hud removeFromSuperview];
        [self.collectionView reloadData];
        self.scrollView.contentSize = CGSizeMake(WIDTH * (self.scrArr.count + 2), 0);
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        self.scrollView.pagingEnabled = YES;
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.scrollView.contentOffset.x == (self.scrArr.count + 1) * SWIDTH) {
        self.scrollView.contentOffset = CGPointMake(SWIDTH, 0);
    }else if (self.scrollView.contentOffset.x == 0) {
        self.scrollView.contentOffset = CGPointMake(self.scrArr.count * SWIDTH, 0);
    }
    
}

- (void)changeAction{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + SWIDTH, 0) animated:YES];
    // 判断是否到当前的最后一张, 如果到了, 需要把偏移量设置到第一张图片的位置
    if (self.scrollView.contentOffset.x == self.scrArr.count * SWIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        HYCPushCityCollReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        
        for (NSInteger i = 0; i < (self.scrArr.count + 2); i++) {
            
            UIImageView *lImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH , 200)];
            //            [lImageView sd_setImageWithURL:[NSURL URLWithString:[self.lArr[i] pic]]];
            [reusableView.scrollView addSubview:lImageView];
            reusableView.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * (self.scrArr.count ) , 0);
            reusableView.scrollView.delegate = self;
            reusableView.scrollView.pagingEnabled = YES;
            [lImageView release];
            self.scrollView = reusableView.scrollView;
        }
        return reusableView;
    }
    return nil;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HYCPushCityCell *collCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    HYCPushCityModel *model = self.arr[indexPath.row];
    collCell.model = model;
    
    self.collectionView.frame = CGRectMake(0, 0, SWIDTH, SHEIGHT);
    
    collCell.layer.shadowColor = [[UIColor blackColor]CGColor];
    collCell.alpha = 0;
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:1];
    collCell.alpha = 1;
    [UIView commitAnimations];
    return collCell;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
